package middleware

import (
	"errors"
	"software/global"
	"software/models/res"
	"strings"

	"github.com/golang-jwt/jwt/v4"

	"software/core"

	"github.com/gin-gonic/gin"
)

// JWTMiddleware 验证 JWT 中间件
func JWTMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头中获取 token
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			res.FailWithMsg("缺少授权标头", c)
			c.Abort()
			return
		}

		// 提取 token
		tokenParts := strings.Split(authHeader, " ")
		if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
			res.FailWithMsg("令牌格式无效,须持有令牌", c)
			c.Abort()
			return
		}

		tokenString := tokenParts[1]

		// 解析并验证 token
		claims, err := core.ParseToken(tokenString)
		if err != nil {
			var ve *jwt.ValidationError
			if errors.As(err, &ve) && ve.Errors&jwt.ValidationErrorExpired != 0 {
				res.FailWithMsg("Token已经失效", c)
				c.Abort()
				return
			}
			res.FailWithMsg("错误的 token: "+err.Error(), c)
			c.Abort()
			return
		}

		// 处理并转换user_id为uint类型
		var adminID uint
		if userID, ok := claims["user_id"]; ok {
			switch v := userID.(type) {
			case float64:
				adminID = uint(v)
			case uint:
				adminID = v
			case int:
				adminID = uint(v)
			default:
				global.Log.Errorf("无效的用户ID类型: %T", userID)
				res.FailWithMsg("无效的用户ID", c)
				c.Abort()
				return
			}
			// 将转换后的uint类型ID存入上下文
			c.Set("user_id", adminID)
		} else {
			global.Log.Error("Token中未找到user_id")
			res.FailWithMsg("无效的Token", c)
			c.Abort()
			return
		}

		// 设置角色信息
		if role, ok := claims["role"]; ok {
			c.Set("role", role)
		}

		// 继续处理请求
		c.Next()
	}
}
